package com.wonderfulWeather.app.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import com.wonderfulWeather.app.WeatherApplication;
import com.wonderfulWeather.app.activity.SplashActivity;
import com.wonderfulWeather.app.model.County;
import com.wonderfulWeather.app.receiver.AutoUpdateReceiver;
import com.wonderfulWeather.app.util.*;

/**
 * Created by kevin on 2014/12/23.
 * 后台自动更新天气服务
 *
 */
public class AutoUpdateService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            new SplashActivity().BeginRequestLocation(new LocationListener() {
                @Override
                public void getLocationSuccessed(County c) {
                    LogUtil.d("onWindowFocusChanged", "get location:" + c.getCounty());
                    WeatherApplication.setCurrentCounty(c);
                    updateWeather(0);
                    //queryWeatherInfo(c.getCode());
                }

                @Override
                public void getLocationError(String ErrorCode) {
                    //Toast.makeText(WeatherActivity.this,"为了更精准的获取天气信息，建议您打开WIFI网络",Toast.LENGTH_SHORT).show();
                }
            },getApplicationContext());
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        int anHour = 30 * 60 * 1000; //半小时
        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
        Intent i = new Intent(this, AutoUpdateReceiver.class);
        PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, i, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pIntent);
        return super.onStartCommand(intent, flags, startId);
    }

    private void updateWeather(final int index)
    {
        SharedPreferences prefs=this.getSharedPreferences(CommonUtility.SHARED_PREF_NAME,MODE_PRIVATE);
        String [] weatherCode=prefs.getString("codes","").split("\\|");
        final int nCount=weatherCode.length;
        String code=weatherCode[index];
        if(code.length()==9) {
            if(CommonUtility.LOCATION_CODE.equals(code))
            {
                code=prefs.getString("location","");
            }
            LogUtil.d("AutoUpdateService","update code="+code);
            String address = CommonUtility.getWeatherUrl(code);
            HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
                @Override
                public void onFinish(String response) {
                    Utility.handleWeatherResponse(AutoUpdateService.this, response);
                    try
                    {
                        Thread.sleep(2000);
                        int nextIndex=index+1;
                        if(nextIndex<nCount) {
                            updateWeather(nextIndex);
                        }
                    }catch (Exception ex)
                    {
                        ex.printStackTrace();
                    }
                }

                @Override
                public void onError(Exception e) {
                    e.printStackTrace();
                }
            });
            address = CommonUtility.getWeatherUrl2(code);
            HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
                @Override
                public void onFinish(String response) {
                    Utility.handleWeatherMoreResponse(AutoUpdateService.this, response);
                }
                @Override
                public void onError(Exception e) {
                    e.printStackTrace();
                }
            });
        }

    }
}
